from flask import Blueprint, request, jsonify
from flask_login import login_required, current_user
from app import db
from app.models.status import StatusUpdate
from app.models.user import User
from app.utils.decorators import manager_required

bp = Blueprint('status', __name__, url_prefix='/api/status')

@bp.route('', methods=['POST'])
@login_required
def update_status():
    """更新工作状态"""
    data = request.get_json()

    required_fields = ['work_status']
    if not all(field in data for field in required_fields):
        return jsonify({'error': 'Missing required fields'}), 400

    valid_statuses = ['on_site', 'remote', 'leave', 'out']
    if data['work_status'] not in valid_statuses:
        return jsonify({'error': f'Invalid status. Must be one of: {", ".join(valid_statuses)}'}), 400

    status_update = StatusUpdate(
        user_id=current_user.id,
        work_status=data['work_status'],
        location=data.get('location'),
        current_task=data.get('current_task'),
        objective_id=data.get('objective_id') if data.get('objective_id') else None,
        notes=data.get('notes')
    )

    db.session.add(status_update)
    db.session.commit()

    return jsonify(status_update.to_dict()), 201

@bp.route('/me', methods=['GET'])
@login_required
def get_my_status():
    """获取我的状态历史"""
    limit = request.args.get('limit', 10, type=int)

    statuses = StatusUpdate.query.filter_by(user_id=current_user.id)\
        .order_by(StatusUpdate.created_at.desc())\
        .limit(limit).all()

    return jsonify([status.to_dict() for status in statuses]), 200

@bp.route('/me/latest', methods=['GET'])
@login_required
def get_my_latest_status():
    """获取我的最新状态"""
    status = StatusUpdate.query.filter_by(user_id=current_user.id)\
        .order_by(StatusUpdate.created_at.desc()).first()

    if not status:
        return jsonify({'message': 'No status updates found'}), 404

    return jsonify(status.to_dict()), 200

@bp.route('/team', methods=['GET'])
@manager_required
def get_team_status():
    """获取团队状态（主管权限）"""
    # 获取所有下属
    team_members = current_user.get_team_members()
    team_member_ids = [member.id for member in team_members] + [current_user.id]

    # 获取每个成员的最新状态
    team_status = []
    for user_id in team_member_ids:
        user = User.query.get(user_id)
        latest_status = StatusUpdate.query.filter_by(user_id=user_id)\
            .order_by(StatusUpdate.created_at.desc()).first()

        team_status.append({
            'user': user.to_dict(),
            'latest_status': latest_status.to_dict() if latest_status else None
        })

    return jsonify(team_status), 200

@bp.route('/user/<int:user_id>', methods=['GET'])
@manager_required
def get_user_status(user_id):
    """获取指定用户的状态历史（主管权限）"""
    user = User.query.get_or_404(user_id)

    # 检查是否是该用户的主管
    team_member_ids = [member.id for member in current_user.get_team_members()]
    if user_id not in team_member_ids and user_id != current_user.id:
        return jsonify({'error': 'You can only view status of your team members'}), 403

    limit = request.args.get('limit', 10, type=int)
    statuses = StatusUpdate.query.filter_by(user_id=user_id)\
        .order_by(StatusUpdate.created_at.desc())\
        .limit(limit).all()

    return jsonify({
        'user': user.to_dict(),
        'statuses': [status.to_dict() for status in statuses]
    }), 200

@bp.route('/user/<int:user_id>/latest', methods=['GET'])
@login_required
def get_user_latest_status(user_id):
    """获取指定用户的最新状态"""
    user = User.query.get_or_404(user_id)

    # 权限检查：只有管理员、主管或用户本人可以查看
    if not current_user.is_manager() and current_user.id != user_id:
        team_member_ids = [member.id for member in current_user.get_team_members()]
        if user_id not in team_member_ids:
            return jsonify({'error': 'Access denied'}), 403

    status = StatusUpdate.query.filter_by(user_id=user_id)\
        .order_by(StatusUpdate.created_at.desc()).first()

    if not status:
        return jsonify(None), 200

    return jsonify(status.to_dict()), 200